/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package spatialmarketplace.cem.dao.implementation;

import java.util.ArrayList;
import java.util.Date;
import spatialmarketplace.cem.dao.CEMNotificationDao;
import spatialmarketplace.cem.dao.DBHandler;
import spatialmarketplace.cem.model.CEMNotification;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.stripes.util.Log;

/**
 *   Implements the Notifications DAO.
 * @author Camila
 */
public class CEMNotificationDaoImpl implements CEMNotificationDao {

    private static final Log logger = Log.getInstance(CEMNotificationDaoImpl.class);
    private Connection conn = null;
    private static CEMNotificationDaoImpl instance = new CEMNotificationDaoImpl();

    public static CEMNotificationDaoImpl getInstance() {
        return instance;
    }

    /**
     * Returns the 10 latest the notifications relevant to the user looking into which groups he belongs to.
     * @param userId
     * @return 
     */
    @Override
    public ArrayList<CEMNotification> getNotifications(Integer userId) {
        DBHandler dbInstance = DBHandler.getInstance();
        ArrayList<CEMNotification> list = new ArrayList<CEMNotification>();
        CEMNotification notification;

        Integer notificationId;
        Integer groupId;
        Integer typeId;
        String actionText;
        String actionLink;
        String typeImageLocation;
        Date date;

        try {
            if (dbInstance != null) {
                String query = new String("SELECT DISTINCT * FROM CEMNotification N, NotificationType T, CEM_GroupMember M "
                        + "WHERE N.typeId = T.typeId AND M.userId = " + userId + " AND M.groupId = N.groupId "
                        + "ORDER BY N.date desc LIMIT 10");
                dbInstance.openConnection();
                ResultSet rs = dbInstance.executeQuery(query);

                try {
                    while (rs.next()) {
                        notificationId = Integer.valueOf(rs.getInt("notificationId"));
                        groupId = Integer.valueOf(rs.getInt("groupId"));
                        typeId = Integer.valueOf(rs.getInt("typeId"));
                        actionText = rs.getString("actionText");
                        actionLink = rs.getString("actionLink");
                        typeImageLocation = rs.getString("typeImageLocation");
                        date = rs.getDate("date");

                        //Create the notification and add it to the list.
                        notification = new CEMNotification(notificationId, groupId, typeId, actionText, actionLink, typeImageLocation, date);
                        list.add(notification);
                    }

                    dbInstance.closeConnection();

                } catch (SQLException ex) {
//                    ex.printStackTrace();
                    Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("Error: " + e);
            logger.error("ERROR: " + CEMNotificationDaoImpl.class.getName() + ", " + e);
        }
        return list;
    }

    /**
     * Creates a notification for a group and type required.
     * @param groupId
     * @param typeId
     * @param actionLink 
     */
    @Override
    public void createNotification(Integer groupId, Integer typeId, String actionLink) {

        //Save the notification to the database with the current date.
        DBHandler dbInstance = DBHandler.getInstance();
        try {
            if (dbInstance != null) {

                String query = new String("INSERT INTO  CEMNotification (groupId, typeId, actionLink, date)"
                        + " values (?, ?, ?, ?)");
                conn = dbInstance.openConnection();

                try {
                    PreparedStatement preparedStatement = null;
                    // PreparedStatements can use variables and are more efficient
                    preparedStatement = conn.prepareStatement(query);
                    // Parameters start with 1
                    preparedStatement.setInt(1, groupId);
                    preparedStatement.setInt(2, typeId);
                    preparedStatement.setString(3, actionLink);
                    preparedStatement.setDate(4, new java.sql.Date(new java.util.Date().getTime()));

                    preparedStatement.execute();

                    dbInstance.closeConnection();

                } catch (SQLException ex) {
                    ex.printStackTrace();
//                    Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("Error: " + e);
            logger.error("ERROR: " + ForumPostDaoImpl.class.getName() + ", " + e);
        }
    }

    public static void main(String args[]) {
        CEMNotificationDaoImpl f = CEMNotificationDaoImpl.getInstance();
        f.createNotification(2, 3, "whatever link");
    }

    @Override
    public CEMNotification getNotification(Integer notId) {
        DBHandler dbInstance = DBHandler.getInstance();
        CEMNotification notification = null;

        Integer notificationId;
        Integer groupId;
        Integer typeId;
        String actionText;
        String actionLink;
        String typeImageLocation;
        Date date;

        try {
            if (dbInstance != null) {
                String query = new String("SELECT DISTINCT * FROM CEMNotification N, NotificationType T, CEM_GroupMember M "
                        + "WHERE N.typeId = T.typeId AND N.notificationId = " + notId + " AND M.groupId = N.groupId ");
                dbInstance.openConnection();
                ResultSet rs = dbInstance.executeQuery(query);

                try {
                    while (rs.next()) {
                        notificationId = Integer.valueOf(rs.getInt("notificationId"));
                        groupId = Integer.valueOf(rs.getInt("groupId"));
                        typeId = Integer.valueOf(rs.getInt("typeId"));
                        actionText = rs.getString("actionText");
                        actionLink = rs.getString("actionLink");
                        typeImageLocation = rs.getString("typeImageLocation");
                        date = rs.getDate("date");
                        //Create the notification and add it to the list.
                        notification = new CEMNotification(notificationId, groupId, typeId, actionText, actionLink, typeImageLocation, date);
                    }

                    dbInstance.closeConnection();

                } catch (SQLException ex) {
//                    ex.printStackTrace();
                    Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("Error: " + e);
            logger.error("ERROR: " + CEMNotificationDaoImpl.class.getName() + ", " + e);
        }
        return notification;
    }
}
